package bin_tree.leetcode;



/**
 * @author yuisama
 * @date 2023/03/24 19:58
 **/
public class Num110_IsBalancedTree {
    public boolean isBalanced(TreeNode root) {
        // base case
        if(root == null || root.left == null && root.right == null) {
            return true;
        }
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        int abs = Math.abs(leftHeight - rightHeight);
        // 找反例
        if (abs > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }
    public int height(TreeNode root) {
        // 1.base case
//        if (root == null) {
//            return 0;
//        }
//        // 总高度 = 1 + Math.max(左子树高度，右子树高度)
//        return 1 + Math.max(height(root.left),height(root.right));
        return root == null ? 0 : 1 + Math.max(height(root.left),height(root.right));
    }

}